#include "AQbuffer.h"
#include "AQthreadpool.h"
#include <iostream>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <string>
#include <set>
#include <pthread.h>

using namespace AQBUFFER;

#define EPOLLSIZE 50
#define IP "101.34.110.235"
#define PORT 9999

void *Work(void *arg);
void *Listen(void *arg);

void setnbmod(int fd)
{
    int flag = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flag | O_NONBLOCK);
}

void Send(int fd, BUFFER &buff)
{
    const void *p = buff.beginRead();
    // fixme
    send(fd, p, buff.readable(), 0);
}

int main()
{
    int sockfd = socket(PF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sockadr;
    sockadr.sin_family = AF_INET;
    sockadr.sin_addr.s_addr = inet_addr(IP);
    sockadr.sin_port = htons(PORT);
    //setnbmod(sockfd);

    if (connect(sockfd, (sockaddr *)&sockadr, sizeof(sockadr)) == -1)
    {
        std::cout << "connect error!" << std::endl;
        return 0;
    }
    pthread_t tid1, tid2;

    pthread_create(&tid2, NULL, Listen, &sockfd);
    pthread_create(&tid1, NULL, Work, &sockfd);
    

    pthread_join(tid1, NULL);

    close(sockfd);
    return 0;
}

void *Work(void *arg)
{
    BUFFER buff;
    int sock = *(int *)arg;
    while (1)
    {
        std::string msg;
        std::getline(std::cin,msg);
        if(msg.size()==0)
        {
            std::cout<<"Cannot send empty message."<<std::endl;
            continue;
        }
        buff.writestring(msg);
        Send(sock, buff);
        buff.fix_readIndex(msg.size()+sizeof(int));
        if (msg == "bye")
            break;
    }
    return NULL;
}

void *Listen(void *arg)
{
    BUFFER buff;
    int sock = *(int *)arg;
    while (1)
    {
        ssize_t n = buff.readFd(sock);
        //std::cout<<"buffsize= "<<buff.size()<<"readIndex= "<<buff.prependable()<<std::endl;
        //std::cout<<n<<" "<<buff.readable()<<std::endl;
        if(n==0)
        {
            std::cout<<"You have been disconnected..."<<std::endl;
            close(sock);
            exit(0);
            break;
        }
        if (buff.readable() > sizeof(int))
        {
            void *p = buff.beginRead();
            int len = 0;
            memcpy(&len,p,sizeof(int));
            buff.nToh(&len,sizeof(int));
            ///std::cout<<n<<" "<<buff.readable()<<" "<<len<<" "<< *(int*)p<<" "<<*((char*)p+4)<<std::endl;
            if (buff.readable() >= len + sizeof(int))
            {
                len = buff.readint();
                std::string msg=buff.readstring(len);
                std::cout <<">>"<<msg << std::endl;
                
            }
        }
    }
}